import asyncio
import time
from aiohttp import ClientSession

# 定义要测试的URL
url = "https://www.baidu.com"

async def fetch_with_pool(session, url):
    async with session.get(url) as response:
        return await response.text()

async def fetch_without_pool(url):
    async with ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

async def main_with_pool():
    tasks = []
    async with ClientSession() as session:
        for _ in range(10000):  # 模拟100个并发请求
            task = asyncio.ensure_future(fetch_with_pool(session, url))
            tasks.append(task)
        results = await asyncio.gather(*tasks)
    return results

async def main_without_pool():
    tasks = []
    for _ in range(10000):  # 模拟100个并发请求
        task = asyncio.ensure_future(fetch_without_pool(url))
        tasks.append(task)
    results = await asyncio.gather(*tasks)
    return results

if __name__ == "__main__":
    # 测试使用连接池的情况
    start_time_pool = time.time()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main_with_pool())
    end_time_pool = time.time()
    print(f"Using connection pool, Total time: {end_time_pool - start_time_pool} seconds")

    # 测试不使用连接池的情况
    start_time_no_pool = time.time()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main_without_pool())
    end_time_no_pool = time.time()
    print(f"Without connection pool, Total time: {end_time_no_pool - start_time_no_pool} seconds")